<?php
namespace Admin\Controller;
use Think\Controller;
class NewsController extends BaseController {

    //搜索框查询
    public function index(){
        $where=array();
        if(IS_POST){
            $start= strtotime(I('POST.statr',0));//判断开始的时间是否存在，不存在则从0开始查询

            if(!empty(I('POST.end'))){
                $end = strtotime(I('POST.end'))+24*60*60;
            }else{
                $end = time();
            }

            $where['crdate'] = array("between","$start,$end");

            if(!empty(I("POST.keywords")))  $where['title'] = array("like", "%".I('POST.keywords')."%");

        }



        $rows = M('news')->field("tp_news.*,tp_category.name")->join("LEFT JOIN __CATEGORY__ ON __CATEGORY__.id = __NEWS__.category")->where($where)->order("crdate desc")->select();


        $this->assign("rows",$rows);
        /*layout('layout');*///加载layout头尾分离文件
        $this->display();//加载模板
    }

    //添加功能方法
    public function insert(){
        //判断是否有post请求
       if(IS_POST){
         $_POST['crdate']= time();

         $res=M('news')->data($_POST)->add();
         if($res){
             $message=array(
                 'error' => 0,
                 'message' => '添加成功',
             );
         }else{
             $message=array(
                 'error'=>1,
                 'message'=>'添加失败',
             );
         }
         $this->ajaxReturn($message);
       }

        $this->display();//加载模板

    }

    //删除功能
    public function del(){
        if(IS_AJAX){
            $id=I("post.id");
            $res=M("news")->delete($id);
            if($res){
                $message=array(
                    'error'=>0,
                    'message'=>'删除成功',
                );
            }else{
                $message=array(
                    'error'=>1,
                    'message'=>'删除失败',
                );
            }
            $this->ajaxReturn($message);
        }
        $this->display();//加载模板
    }

    //修改
    public function update($id){
        if(IS_AJAX){

            $_POST["tstamp"]=time();
            $res= M("news")->where(array(id=>$id))->save($_POST);
            if($res){
            $message = array(
                "error"=>0,
                "message"=>"修改失败",
            );
        }else{
            $message = array(
                "error"=>1,
                "message"=>"修改成功",
            );
        }
        $this->ajaxReturn($message);
    }

    $rows = M("news")->where(array(id=>$id))->find();
        $category = M("category")->where(array("pid"=>1))->select();
        $this->assign("rows",$rows);
        $this->assign("category",$category);
        $this->display();
    }
    //导出
    public function export(){
    D("news")->look();
    }
}